import { useRef, useEffect } from 'react'
import EditorBlock from './editor-block'
import './editor.scss'
import Material from './material'

function Editor(props) {
  let { data, changeData } = props

  const ref = useRef(null)
  let currentComponent = null
  // const [currentComponent, setCurrentComponent] = useState(null)

  const dragenter = (e) => {
    e.dataTransfer.dropEffect = 'move'
  }
  const dragover = (e) => {
    e.preventDefault()
  }
  const dragleave = (e) => {
    e.dataTransfer.dropEffect = 'none'
  }
  const drop = (e) => {
    const newData = {
      ...data,
      blocks: [
        ...data.blocks,
        {
          top: e.offsetY,
          left: e.offsetX,
          zIndex: 1,
          key: currentComponent.key,
          alignCenter: true,
        },
      ],
    }
    changeData(newData)
    const targetNode = ref.current
    targetNode.removeEventListener('dragenter', dragenter)
    targetNode.removeEventListener('dragover', dragover)
    targetNode.removeEventListener('dragleave', dragleave)
    targetNode.removeEventListener('drop', drop)
  }

  const onDragStart = (e, component) => {
    // dragenter 进入元素中，增加一个移动标识
    // dragover 在目标元素经过，必须阻止默认事件，否则不能触发drop
    // dragleave 离开元素，需要增加一个禁用标识
    // drop 松手的时候，生成一个组件
    const targetNode = ref.current
    targetNode.addEventListener('dragenter', dragenter)
    targetNode.addEventListener('dragover', dragover)
    targetNode.addEventListener('dragleave', dragleave)
    targetNode.addEventListener('drop', drop)
    currentComponent = component
  }

  // useEffect(() => {
  //   return () => {
  //     const targetNode = ref.current
  //     if (targetNode) {
  //       targetNode.removeEventListener('dragenter', dragenter)
  //       targetNode.removeEventListener('dragover', dragover)
  //       targetNode.removeEventListener('dragleave', dragleave)
  //       targetNode.removeEventListener('drop', drop)
  //     }
  //   }
  // }, [])

  return (
    <div className="editor">
      {/* 左侧物料区 */}
      <div className="editor-left">
        <Material onDragStart={onDragStart} />
      </div>
      <div className="editor-container">
        <div className="editor-container-navbar">菜单</div>
        {/* 负责滚动 */}
        <div className="editor-container-canvas">
          {/* 负责产生内容区域 */}
          <div className="editor-container-canvas-content" ref={ref}>
            {data.blocks.map((block, index) => {
              return <EditorBlock block={block} index={index} key={index} />
            })}
          </div>
        </div>
      </div>
      <div className="editor-right">editor-right</div>
    </div>
  )
}

export default Editor
